<template>
  <div class="page-container">
    <div class="page-card-container flex-row">
      <div style="width: 20%" v-global-loading="loadingOrg">
        <a-tree
          v-if="orgArr && orgArr.length"
          v-model:selectedKeys="treeInfo.selectedKeys"
          default-expand-all
          :tree-data="orgArr"
          @select="treeSelect"
        >
          <template #title="{title, key}">
            <span>{{ title }}</span>
          </template>
        </a-tree>
      </div>
      <div class="flex1">
        <a-form class="mb-10" :model="pageSet" layout="inline">
          <a-form-item label="机构名称">
            <a-input v-model:value="pageSet.name" allow-clear />
          </a-form-item>
          <a-form-item>
            <div class="flex-row-xy-center">
              <div
                class="commonBtn-primary mr-10"
                @click="loadPagination(true)"
              >
                搜索
              </div>
              <div class="commonBtn-primary mr-10" @click="goHandle(1)">
                新增
              </div>
            </div>
          </a-form-item>
        </a-form>
        <a-table
          size="small"
          row-key="id"
          :loading="tableLoading"
          :dataSource="tableData"
          :columns="columns"
          bordered
          :pagination="false"
        >
          <template #bodyCell="{text, record, index, column}">
            <div
              class="flex-row-xy-center c-primaryColor fs-12"
              v-if="column.title == '操作'"
            >
              <span class="pointer mr-10" @click="goHandle(2, record)"
                >编辑</span
              >
              <span class="pointer" @click="goHandle(3, record, index)"
                >删除</span
              >
            </div>
          </template>
        </a-table>
        <Pagination
          class="mt-10"
          :page-set="pageSet"
          :load-pagination="loadPagination"
        ></Pagination>
      </div>

      <a-drawer
        width="50%"
        v-model:open="showModal"
        :title="handleTitle"
        :destroyOnClose="true"
      >
        <a-form ref="formRef" :model="form" :label-col="{span: 8}">
          <a-row>
            <!-- <a-col :span="12">
              <a-form-item
                label="机构类型"
                name="orgType"
                :rules="[
                  {
                    required: true,
                    message: '请选择机构类型',
                    trigger: 'change'
                  }
                ]"
              >
                <a-select
                  allow-clear
                  v-model:value="form.orgType"
                  style="width: 100%"
                  placeholder="请选择机构类型"
                >
                  <a-select-option
                    :value="item.code"
                    :key="index"
                    v-for="(item, index) in getDicValue('org_type')"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item
                label="机构名称"
                name="name"
                :rules="[
                  {
                    required: true,
                    message: '请填写机构名称',
                    trigger: 'change'
                  }
                ]"
              >
                <a-input
                  v-model:value="form.name"
                  placeholder="请填写机构名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="唯一编码"
                name="code"
                :rules="[
                  {
                    required: true,
                    message: '请填写唯一编码',
                    trigger: 'change'
                  }
                ]"
              >
                <a-input
                  v-model:value="form.code"
                  placeholder="请填写唯一编码"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="上级机构"
                name="pid"
                :rules="[
                  {
                    required: false,
                    message: '请选择上级机构',
                    trigger: 'change'
                  }
                ]"
              >
                <a-tree-select
                  v-model:value="form.pid"
                  style="width: 100%"
                  :dropdown-style="{maxHeight: '400px', overflow: 'auto'}"
                  placeholder="请选择上级机构"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="orgArr"
                >
                  <template #title="item">
                    {{ item.title }}
                  </template>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="排序">
                <a-input
                  type="number"
                  v-model:value="form.sortId"
                  placeholder="请填写排序"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="备注">
                <a-input v-model:value="form.remark" placeholder="请填写备注" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <template #footer>
          <div class="flex-row-xy-center">
            <a-button style="margin-right: 20px" @click="showModal = false"
              >取消</a-button
            >
            <a-button type="primary" @click="showModalCon">提交</a-button>
          </div>
        </template>
      </a-drawer>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {
  orgAdd,
  orgDelete,
  orgDetail,
  orgEdit
} from "@/api/configCenter/organization/institution";
import {orgTree, posList} from "@/api/configCenter/auth/people";
import {orgPage} from "@/api/configCenter/organization/institution";

import useAppStore from "@/store/app";
import {Modal} from "ant-design-vue";
import Pagination from "@/components/pagination/Pagination.vue";
import {getDicValue} from "@/utils/common";

const pageSet = ref({
  pageNo: 1,
  pageSize: 20,
  total: 0,
  pid: null
});
const tableData = ref([]); //表格数据
const tableLoading = ref(false);
const form = ref({});
const formRef = ref();
const treeInfo = ref({
  selectedKeys: []
});
const loadingOrg = ref(false);

//获取表格数据
const loadPagination = (reset = false) => {
  tableLoading.value = true;
  if (reset) {
    tableData.value = [];
    pageSet.value.pageNo = 1;
  }
  orgPage(pageSet.value)
    .then((res) => {
      tableLoading.value = false;
      tableData.value = res.data.rows;
      pageSet.value.total = res.data.totalRows;
    })
    .catch((err) => {
      tableLoading.value = false;
    });
};

loadPagination();

const treeSelect = (selectedKeys, e) => {
  if (e.selected) {
    pageSet.value.pid = e.node.id;
  } else {
    pageSet.value.pid = null;
  }
  loadPagination(true);
};

//机构列表
const orgArr = ref([]);
const loadOrgTree = () => {
  loadingOrg.value = true;
  orgTree()
    .then((res) => {
      orgArr.value = res.data;
      loadingOrg.value = false;
    })
    .catch((err) => {
      loadingOrg.value = false;
    });
};
loadOrgTree();

//职位列表
const posArr = ref([]);
const getPosList = () => {
  posList().then((res) => {
    posArr.value = res.data;
  });
};
getPosList();

const showModal = ref(false);
const handleTitle = ref<string>();
const handleType = ref<number>();
const goHandle = (type: number, info?: any, index?: number) => {
  handleType.value = type;
  form.value = {};
  if (formRef.value) {
    //重置验证
    formRef.value.clearValidate();
  }
  if (type === 1) {
    handleTitle.value = "新增";
    showModal.value = true;
    return;
  }
  if (type === 2) {
    handleTitle.value = "编辑";
    useAppStore.loading = true;
    orgDetail({id: info.id}).then((res) => {
      form.value = res.data;
      showModal.value = true;
      useAppStore.loading = false;
    });
    return;
  }
  if (type === 3) {
    Modal.confirm({
      title: "提示",
      content: "确定要删除吗",
      onOk() {
        useAppStore.loading = true;
        orgDelete({id: info.id}).then((res) => {
          loadPagination();
          loadOrgTree();
          useAppStore.loading = false;
        });
      }
    });
    return;
  }
};

const showModalCon = () => {
  if (handleType.value === 1) {
    formRef.value.validate().then((res) => {
      useAppStore.loading = true;
      orgAdd(form.value).then((res) => {
        loadPagination();
        loadOrgTree();
        showModal.value = false;
        useAppStore.loading = false;
      });
    });
  }
  if (handleType.value === 2) {
    formRef.value.validate().then((res) => {
      useAppStore.loading = true;
      orgEdit(form.value).then((res) => {
        loadPagination();
        loadOrgTree();
        showModal.value = false;
        useAppStore.loading = false;
      });
    });
  }
};

const columns = [
  {
    title: "序号",
    dataIndex: "name",
    align: "center",
    customRender: function ({index}) {
      return index + 1;
    },
    width: 80
  },
  {
    title: "机构名称",
    dataIndex: "name",
    align: "center"
  },
  // {
  //   title: "机构类型",
  //   dataIndex: "orgType",
  //   align: "center",
  //   customRender({text}) {
  //     return text + "级";
  //   }
  // },
  {
    title: "唯一编码",
    dataIndex: "code",
    align: "center"
  },
  {
    title: "排序",
    dataIndex: "sortId",
    align: "center"
  },
  {
    title: "备注",
    dataIndex: "remark",
    align: "center"
  },
  {
    title: "操作",
    align: "center",
    width: 100,
    fixed: "right"
  }
];
</script>

<style lang="less" scoped></style>
